package com.lee.dynamic.service.impl;

import com.lee.dynamic.config.MasterSlave;
import com.lee.dynamic.mapper.PersonMapper;
import com.lee.dynamic.model.Person;
import com.lee.dynamic.service.IPersonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static com.lee.dynamic.config.DataSourceType.MASTER;

@Service
@Slf4j
public class PersonServiceImpl implements IPersonService {

    @Autowired
    private PersonMapper personMapper;

    @Override
    public List<Person> listPerson() {
        log.info("list person...");
        List<Person> persons = personMapper.listPerson();
        return persons;
    }

    @Override
    @MasterSlave(MASTER)
    public List<Person> listMasterPerson() {
        log.info("list person from master ...");
        List<Person> persons = personMapper.listPerson();
        return persons;
    }

    @Override
    @MasterSlave(MASTER)
    @Transactional
    public int update(int id, int age) {
        log.info("update person, id = {}", id);
        int count = personMapper.updateById(id, age);
        if (count == 1) {
            throw new RuntimeException("手动异常, 验证事务");
        }
        return count;
    }
}
